﻿using System;

using Sunyi.Project.WebPoint.Configuration;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.ServiceAccess;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class TokenManager
    {
        public Token SelectByUserName(string userName)
        {
            var token = controller.SelectByUserName(userName);

            if (token != null && (!token.IsActive || token.IsExpired))
            {
                controller.Erasure(token.Id);
                token = null;
            }

            return token;
        }

        public void Erasure(Guid tokenId)
        {
            controller.Erasure(tokenId);
        }

        public bool VerifyUser(string userName, string accessCode)
        {
            bool flag = false;
            var token = this.SelectByUserName(userName);

            if (token != null)
            {
                flag = VerifyToken(token, accessCode);
            }
            else
            {
                if (SystemConfiguration.PersonnelServiceEnabled)
                {
                    var serviceProxy = new SecurityTokenServiceProxy();
                    flag = serviceProxy.VerifyAccessCode(userName, accessCode);
                }
            }

            return flag;
        }

        public bool VerifyToken(Token token, string accessCode)
        {
            return ServiceAccessHelper.ValidateAccessCode(token.SecurityKey, accessCode);
        }
    }
}
